package com.zsd.android.common

import io.reactivex.disposables.Disposable
import java.lang.ref.WeakReference

abstract class BasePresenter<V : IBaseView, M : BaseModel<*>>(mView: V) {

    protected val mReference: WeakReference<V>?
    protected val mModel: M
    protected val disposalbes: ArrayList<Disposable>

    init {
        mReference = WeakReference(mView)
        mModel = getModel()
        disposalbes = ArrayList()
    }

    fun getView(): V? {
        return mReference?.get()
    }

    /**
     * 统一处理返回状态码
     *
     * @param code 状态码
     * @return 错误状态码true，正确状态码false
     */
    protected fun handleResponseCode(code: Int): Boolean {
        if (0 != code) {
            return true
        }
        return false
    }

    fun destroy() {
        for (disposable in disposalbes) {
            if (disposable != null && !disposable.isDisposed) {
                disposable.dispose()
            }
        }
        disposalbes.clear()
        mReference?.clear()
    }

    abstract fun getModel(): M
}